#include "StdAfx.h"
#include "ChunkModelDebugMesh.h"

#include "d3dx9mesh.h"
#include "D3DRenderer.h"

#include "chunkmanager.h"

#include "UtilityFuncKit.h"

using namespace ChunkSystem;
using namespace Common;

ChunkModelDebugMesh::ChunkModelDebugMesh( ChunkSystem::ChunkModel* pModelItem )
	:m_pModelItem(pModelItem),m_pD3DMesh(NULL)
{
	assert( pModelItem != NULL );
}


ChunkModelDebugMesh::~ChunkModelDebugMesh(void)
{
	if( m_pD3DMesh != NULL )
		m_pD3DMesh->Release();
}

void ChunkModelDebugMesh::Load( ChunkSystem::IRenderer* pRenderer )
{
	std::string strModelFullPath;
	std::stringstream ss;
	ss << ChunkManager::GetInstance().GetResPath() << "/" << ChunkManager::GetInstance().GetSpacePath() << "/" << m_pModelItem->GetResPath();
	ss >> strModelFullPath;
	 
	D3DRenderer* pD3DRenderer = static_cast<D3DRenderer*>(pRenderer);
	if( pD3DRenderer == NULL )
		return;

	if( D3DXLoadMeshFromXA( strModelFullPath.c_str(), D3DXMESH_MANAGED, pD3DRenderer->GetD3DDevice(), NULL, NULL, NULL, NULL, &m_pD3DMesh ) != S_OK )
		return;
}

void ChunkModelDebugMesh::Unload( void )
{
}

void ChunkModelDebugMesh::Draw( ChunkSystem::IRenderer* pRenderer )
{
	D3DRenderer* pD3DRenderer = static_cast<D3DRenderer*>(pRenderer);
	if( pD3DRenderer == NULL || m_pD3DMesh == NULL )
		return;

	LPDIRECT3DDEVICE9 pDevice = pD3DRenderer->GetD3DDevice();
	EnterCriticalSection(&m_CriticalSection);

	Matrix4 matMeshWorld = m_pModelItem->GetWorldTM();
	D3DXMATRIX matDXMeshWorld = UtilityFuncKit::Convert( matMeshWorld );

	pDevice->SetTransform( D3DTS_WORLD, &matDXMeshWorld );

	pDevice->SetRenderState( D3DRS_FILLMODE, D3DFILL_WIREFRAME );

	if( m_pD3DMesh->DrawSubset( 0 ) != S_OK )
		assert(false);

	pDevice->SetRenderState( D3DRS_FILLMODE, D3DFILL_SOLID );

	pDevice->SetTransform( D3DTS_WORLD, D3DXMatrixIdentity( &matDXMeshWorld ) );

	LeaveCriticalSection(&m_CriticalSection);
}
